package com.strive.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.strive.db.properties.MybatisPlusAutoFillProperties;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/2/21 10:49
 * @Version 1.0
 */
public class DateMetaObjectAutoFillHandler implements MetaObjectHandler {
    private MybatisPlusAutoFillProperties autoFillProperties;

    public DateMetaObjectAutoFillHandler(MybatisPlusAutoFillProperties autoFillProperties){
        this.autoFillProperties = autoFillProperties;
    }

    /**
     * 是否启用插入填充
     * @return
     */
    @Override
    public boolean openInsertFill() {
        return autoFillProperties.getEnableInsertFill();
    }

    /**
     * 是否启用更新填充
     * @return
     */
    @Override
    public boolean openUpdateFill() {
        return autoFillProperties.getEnableUpdateFill();
    }

    /**
     * 插入填充判空
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(autoFillProperties.getCreateTimeFiled(), metaObject);
        Object updateTime = getFieldValByName(autoFillProperties.getUpdateTimeFiled(), metaObject);

        Date date = new Date();
        if(createTime == null){
            setFieldValByName(autoFillProperties.getCreateTimeFiled(),date,metaObject);
        }

        if(updateTime == null){
            setFieldValByName(autoFillProperties.getUpdateTimeFiled(),date,metaObject);
        }

    }

    /**
     * 更新填充字段
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(autoFillProperties.getUpdateTimeFiled(),new Date(),metaObject);
    }
}
